<template>
	<swiper class="swiper-list" @change="change" :current='tabIndex'>
		<swiper-item class="swiper-list-item" v-for="(item,index) in tabLsit" :key="index">
			<swiper-list-item :list='article[index]' :load='load[index]' @loadmore="loadmore"></swiper-list-item>
		</swiper-item>
	</swiper>
</template>

<script>
	import swiperListItem from './swiper-list-item.vue';
	export default {
		name: "swiper-list",
		components: {
			swiperListItem
		},
		props: {
			tabLsit: {
				type: Array,
				default () {
					return []
				}
			},
			tabIndex: {
				type: Number,
				default: 0
			}
		},
		watch: {
			tabLsit(newVal) {
				if (newVal.length === 0) return
				this.article = {}
				this.laod = {}
				this.loadData(this.tabIndex)
			}
		},
		// 组件只能用created(), 页面用onLoad()
		created() {
			uni.$on('update_article',(e)=>{
				if(e === 'follow'){
					this.article = {}
					this.laod = {}
					this.loadData(this.tabIndex)
				}
			})
		},
		destroyed() {
			// 移除监听事件
			uni.$off('update_article');
		},
		data() {
			return {
				articleList: [],
				article: {},
				load:{},
				pageSize: 10
			};
		},
		methods: {
			// 监听swiper滑动事件
			change(e) {
				let current = e.detail.current
				this.$emit('swiperListChange', current)
				// 当数据存在 或 长度为0 时,才去请求数据
				if(!this.article[current] || this.article[current].length===0){
					this.loadData(current)
				}
			},
			loadData(current) {
				if(!this.load[current]){
					this.load[current] = {
						page: 1,
						loading:'loading'
					}
				}
				this.$api.getArticle({
					name: this.tabLsit[current].name,
					page: this.load[current].page,
					pageSize:this.pageSize
				}).then(res => {
					let {
						data
					} = res
					// 没有数据
					if(data.length === 0){
						let load = {}
						load.loading = 'noMore'
						load.page = this.load[current].page
						this.$set(this.load, current,load)
						// 强制渲染页面
						this.$forceUpdate()
						return
					}
					let list = this.article[current] || []
					list.push(...data)
					// 懒加载,强制vue刷新页面
					this.$set(this.article, current, list)
				})
			},
			loadmore(){
				if(this.load[this.tabIndex].loading === 'noMore') return
				  this.load[this.tabIndex].page++
				  this.loadData(this.tabIndex)
			}
		}
	}
</script>

<style lang="scss" scoped>
	.swiper-list {
		height: 100%;
		flex: 1;

		.swiper-list-item {
			// height: 100%;
			// overflow: hidden;

			.scroll-list {
				height: 100%;
			}
		}
	}
</style>
